package org.coderk.mybatis.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * @author: TanJingyu
 * @create: 2021-04-05 09:13
 **/
@RestController
@RequestMapping("/queue")
public class BlockingQueueTest {
    private static final BlockingDeque<Integer> willPushCodesLater = new LinkedBlockingDeque<>();
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @GetMapping
    public String queue(Integer count) throws InterruptedException {
        System.out.println("添加任务 " + Thread.currentThread().getName());
        for (int i = 0; i < count; i++) {
            willPushCodesLater.putLast(i);
        }
        return "success...";
    }

//    @PostConstruct
    @Async
    public void execute() throws InterruptedException {

        for (; ;) {
            int s = willPushCodesLater.takeFirst();
            System.out.println("执行任务：" + Thread.currentThread().getName() + "  " + s);
        }

//        threadPoolTaskExecutor.execute(() -> {
//            try {
//                for (; ;) {
//                    int s = willPushCodesLater.takeFirst();
//                    System.out.println("执行任务：" + Thread.currentThread().getName() + "  " + s);
//                }
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        });
    }
}
